package com.zy.explore.generator.infrastructure.core.base;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * description 模块基类
 *
 * @author 🇨🇳中国印🇨🇳
 * @date 2021年04月11日 19:47
 */
@Slf4j
public class BaseModule {

    private static final String ENCODING = "UTF-8";

    protected static Template getTemplate(String ftl, String ftlPath) throws IOException {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
        String userDir = System.getProperty("user.dir");
        File file = new File(userDir + ftlPath);
        cfg.setDirectoryForTemplateLoading(file);
        cfg.setDefaultEncoding(ENCODING);
        return cfg.getTemplate(ftl, ENCODING);
    }

    protected static void writeFile(File file, String ftl, String ftlPath, Object dataModel) throws IOException, TemplateException {
        if (file == null) {
            log.error("文件不存在");
            return;
        }
        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
        }
        if (StringUtils.isEmpty(ftl)) {
            return;
        }
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file));
        try {
            getTemplate(ftl, ftlPath).process(dataModel, outputStreamWriter);
        } finally {
            outputStreamWriter.flush();
            outputStreamWriter.close();
        }
    }

}
